package com.grakol.parallel.samples.tests;

import java.util.Arrays;
import java.util.List;

import com.grakol.parallel.samples.IFunction;

/**
 * Sorts array of integers.
 * 
 * @author LK
 */
public class SimpleSortFunction implements IFunction<int[]> {
	private int[] _result;
	
	public SimpleSortFunction( int[] array, int fromPos, int length ) {
		_result = new int[length];
		System.arraycopy( array, fromPos, _result, 0, length );
	}

	@Override
	public int[] getResult() {
		return _result;
	}

	@Override
	public int[] mergeResults( List<int[]> arrays ) {
		int mSize = 0;
		for( int[] array : arrays ) 
			mSize += array.length;
		int[] mArray = new int[mSize];
		int[] indexes = new int[arrays.size()];
		Arrays.fill( indexes, 0 );
		for( int mIndex = 0; mIndex < mSize; mIndex++ ) {
			// find min value among all arrays at current indexes
			int vMin = Integer.MAX_VALUE;
			int nMin = -1;
			int n = 0;
			for( int[] array : arrays ) {
				if( indexes[n] < array.length ) {
					int v = array[indexes[n]];
					if( v <= vMin ) {
						vMin = v;
						nMin = n;
					}
				}
				n++;
			}
			if( nMin >= 0 ) {
				// set value in merged array
				mArray[mIndex] = vMin;
				// increase index in appropriate source array
				indexes[nMin]++;
			} else
				break;
		}
		return mArray;
	}

	@Override
	public void perform() {
		Arrays.sort( _result );
	}

}
